package tree.leetcode_297_hard;

import java.util.LinkedList;
import java.util.Queue;

public class DFSSolution {
    /*
        序列化
     */
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        return dfs(root, sb).toString();
    }

    public StringBuilder dfs(TreeNode root, StringBuilder str) {
        if (root == null) {
            return str.append("null,");
        }
        str.append(root.val).append(",");
        dfs(root.left, str);
        dfs(root.right, str);
        return str;
    }

    /*
        反序列化
     */
    public TreeNode deserialize(String data) {
        String[] str = data.split(",");
        Queue<String> queue = new LinkedList<>();
        for (int i = 0; i < str.length; i++) {
            queue.add(str[i]);
        }
        return dfs(queue);
    }

    public TreeNode dfs(Queue<String> queue) {
        String value = queue.poll();
        if (value.equals("null")) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(value));
        root.left = dfs(queue);
        root.right = dfs(queue);
        return root;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        DFSSolution dfsSolution = new DFSSolution();
        String s = dfsSolution.serialize(root);
        System.out.println(s);
        TreeNode node = dfsSolution.deserialize(s);
        System.out.println(node);
    }
}
